package com.apop.common.component;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.apop.common.model.Result;
import com.apop.common.model.CodeMsg;
import com.apop.hrss.home.componet.PostProcessor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.apop.common.model.CodeMsg.REQUEST_PARAMS_NOT_FOUND;

/**
 * @ClassName HttpSender
 * @Author Jiayi Zheng
 * @Date 2021/12/7 17:08
 * @Description: todo
 * @Version V1.0
 */
@Setter
@Getter
@Slf4j
public class HttpSender {

    private String address;

    /**
     * 发送请求V2
     *
     * @param url
     * @param paramMap
     * @param
     * @return
     */
    public static Object sendRequest(String url, Map<String, Object> paramMap,String method) {
        log.debug("发送http请求 >>>>>>>>>>>>>>>>>>>> ");
        PostProcessor postProcessor = SpringUtil.getBean(PostProcessor.class);
        String result = "";
        log.debug("请求地址："+url);

        try {
            if ("post".equals(method)) {
                String body = JSONObject.toJSONString(paramMap);
                log.debug("请求参数：{}", body);
                result = HttpUtil.post(url, body);
            } else {
                log.debug("请求参数：" + paramMap);
                result = HttpUtil.get(url, paramMap);
            }
            log.debug("原始报文：{} ", result);
            // JsonString 转 JsonObj
            JSONObject jsonObject = JSON.parseObject(result);

            // 后台调用失败处理
            if (jsonObject.get("code") != null && (Integer) jsonObject.get("code") < 0) {
                return Result.error(CodeMsg.BACK_END_ERROR, (String) jsonObject.get("msg"));
            }

            return Result.success(jsonObject.get("data"));
        }
        catch (JSONException e) {
            String htm = "";
            String pattern = "parameter.*present";
            Pattern r = Pattern.compile(pattern);
            Matcher matcher = r.matcher(result);
            // 获得结果集
            while (matcher.find()) {
                htm = matcher.group(0);
            }
            return Result.error(REQUEST_PARAMS_NOT_FOUND, htm);
        }


    }
}
